package com.duoec.magichour.service.impl;

import com.duoec.magichour.mapper.ArticlePhotoMapper;
import com.duoec.magichour.pojo.ArticlePhoto;
import com.duoec.magichour.service.ArticlePhotoService;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Created by ycoe on 17/6/28.
 */
@Service
public class ArticlePhotoServiceImpl implements ArticlePhotoService {
    @Autowired
    private ArticlePhotoMapper articlePhotoMapper;

    /**
     * 会删除不在urls里的图片，再插入不存在的图片
     *
     * @param articleId 文章ID
     * @param urls      图片URLs
     */
    @Override
    public void setArticlePhotos(long articleId, Set<String> urls) {
        List<ArticlePhoto> photos = articlePhotoMapper.listArticlePhotos(articleId);
        Set<String> existUrls = Sets.newHashSet();
        //判断不存在的，进行删除
        if (photos != null && !photos.isEmpty()) {
            photos.forEach(articlePhoto -> {
                if (urls.contains(articlePhoto.getPhotoUrl())) {
                    //已经存在，不理会
                    existUrls.add(articlePhoto.getPhotoUrl());
                } else {
                    // 不存在，需要删除
                    articlePhotoMapper.deleteById(articlePhoto.getId());
                }
            });
        }

        urls.forEach(url -> {
            if (!existUrls.contains(url)) {
                // 不存在，需要插入
                ArticlePhoto articlePhoto = new ArticlePhoto();
                articlePhoto.setArticleId(articleId);
                articlePhoto.setPhotoUrl(url);
                articlePhotoMapper.insertSelective(articlePhoto);
            }
        });
    }
}
